package com.project.pet.controller.web;

import cn.hutool.core.util.IdUtil;
import com.project.pet.common.Constant;
import com.project.pet.common.ResponseData;
import com.project.pet.service.CommonService;
import com.project.pet.utils.ResponseDataUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

@RestController("webCommonController")
@RequestMapping("/api/web/common")
public class CommonController {
    @Autowired
    private CommonService commonService;

    @PostMapping("/upload")
    public ResponseData<Object> upload(@RequestBody HashMap<String,Object> map) {
        return commonService.upload(map.get("base64").toString());
    }

    @PostMapping("/fileUpload")
    public ResponseData<Object> fileUpload(@RequestPart(value = "file") MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String suffix =  fileName.substring(fileName.lastIndexOf("."));
        String newName = IdUtil.simpleUUID()+suffix;
        HashMap<String, String> data = new HashMap<>();
        data.put("src", Constant.FILE_URL_PREFIX+newName);
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(Constant.FILE_HOME+newName));
        return ResponseDataUtil.buildSuccess(data);
    }
}
